package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.SystemRoleManager;
import com.fish.anne.model.SystemRole;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class SystemRoleAction extends BaseAction implements Preparable {
    private SystemRoleManager systemRoleManager;
    private List systemRoles;
    private SystemRole systemRole;
    private Long  roleId;

    public void setSystemRoleManager(SystemRoleManager systemRoleManager) {
        this.systemRoleManager = systemRoleManager;
    }

    public List getSystemRoles() {
        return systemRoles;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String systemRoleId = getRequest().getParameter("systemRole.roleId");
            if (systemRoleId != null && !systemRoleId.equals("")) {
                systemRole = systemRoleManager.get(new Long(systemRoleId));
            }
        }
    }

    public String list() {
        systemRoles = systemRoleManager.getAll();
        return SUCCESS;
    }

    public void setRoleId(Long  roleId) {
        this. roleId =  roleId;
    }

    public SystemRole getSystemRole() {
        return systemRole;
    }

    public void setSystemRole(SystemRole systemRole) {
        this.systemRole = systemRole;
    }

    public String delete() {
        systemRoleManager.remove(systemRole.getRoleId());
        saveMessage(getText("systemRole.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (roleId != null) {
            systemRole = systemRoleManager.get(roleId);
        } else {
            systemRole = new SystemRole();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (systemRole.getRoleId() == null);

        systemRoleManager.save(systemRole);

        String key = (isNew) ? "systemRole.added" : "systemRole.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}